#!/usr/bin/env python3
# scripts/stop_services.py
import os
import signal
import subprocess
import time
from pathlib import Path

def stop_service(pid_file, service_name):
    """停止指定服务"""
    if not pid_file.exists():
        print(f"PID file for {service_name} not found")
        return False
    
    try:
        # 读取PID
        with open(pid_file, 'r') as f:
            pid = int(f.read().strip())
        
        # 检查进程是否存在
        result = subprocess.run(['ps', '-p', str(pid)], capture_output=True)
        if result.returncode == 0:
            # 发送终止信号
            print(f"Sending SIGTERM to {service_name} (PID: {pid})")
            os.kill(pid, signal.SIGTERM)
            
            # 等待进程优雅终止（最多10秒）
            timeout = 10
            while timeout > 0 and subprocess.run(['ps', '-p', str(pid)], capture_output=True).returncode == 0:
                time.sleep(1)
                timeout -= 1
            
            # 如果进程仍未终止，强制杀死
            if subprocess.run(['ps', '-p', str(pid)], capture_output=True).returncode == 0:
                print(f"Force killing {service_name} (PID: {pid})")
                os.kill(pid, signal.SIGKILL)
            
            print(f"Stopped {service_name} (PID: {pid})")
            
            # 删除PID文件
            pid_file.unlink()
            return True
        else:
            print(f"Process for {service_name} (PID: {pid}) not found")
            # 删除不存在的PID文件
            pid_file.unlink()
            return False
    except Exception as e:
        print(f"Error stopping {service_name}: {e}")
        # 即使出错也删除PID文件
        if pid_file.exists():
            pid_file.unlink()
        return False

def main():
    # PID文件路径
    pid_dir = Path("runtime/pids")
    
    if not pid_dir.exists():
        print("No services are running (PID directory not found)")
        return
    
    # 停止所有服务
    embedding_pid = pid_dir / "qwen3-embedding-0.6b.pid"
    reranker_pid = pid_dir / "qwen3-reranker-0.6b.pid"
    
    embedding_stopped = stop_service(embedding_pid, "qwen3-embedding-0.6b")
    reranker_stopped = stop_service(reranker_pid, "qwen3-reranker-0.6b")
    
    if embedding_stopped or reranker_stopped:
        print("Services stopped successfully")
    else:
        print("No services were running")

if __name__ == "__main__":
    main()